package com.example.demofdfs.example.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 存储商品
 * @author chenyq
 * @email 806512500@qq.com
 * @date 2019年1月5日
 */
public class CommodityStore implements Store {

	/**
	 * 存储商品的的列表
	 */
	private List<Commodity> store = new ArrayList<>();
	
	/**
	 * 锁
	 */
	private final Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	
	/**
	 * 放入商品时, 会锁顶这个列表, 添加完成后会唤醒等待的线程
	 */
	@Override
	public void put(Commodity commodity) {
		lock.lock();
		try {
			store.add(commodity);
			condition.signal();
		} finally {
			lock.unlock();
		}
	}
	
	/**
	 * 获取商品, 会移除列表中的这个元素, 假若列表没有这个元素, 则等待
	 */
	@Override
	public Commodity get() {
		lock.lock();
		try {
			if (store.isEmpty()) {
				condition.await();
			}
			return store.remove(0);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return get();
	}
}
